package com.huluobo.a2204kotlinshopping.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2204kotlinshopping.R
import com.huluobo.a2204kotlinshopping.adapter.HomeGoodsAdapter
import com.huluobo.a2204kotlinshopping.adapter.HomeHotAdapter
import com.huluobo.a2204kotlinshopping.adapter.HomeNavAdapter
import com.huluobo.a2204kotlinshopping.databinding.FragmentHomeBinding
import com.huluobo.a2204kotlinshopping.detail.DetailActivity
import com.huluobo.a2204kotlinshopping.search.SearchActivity
import com.huluobo.a2204kotlinshopping.utils.ImageUtils
import com.huluobo.base.bean.HomeGoodsBean
import com.huluobo.base.bean.HomeNavBean
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMFragment
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader

class HomeFragment : BaseMVVMFragment<FragmentHomeBinding, HomeViewModel>() {
    //商品的adapter
    private lateinit var homeGoodsAdapter: HomeGoodsAdapter

    //商品的数据源
    private val homeGoodsList = mutableListOf<HomeGoodsBean>()

    //导航的adapter
    private lateinit var navAdapter: HomeNavAdapter

    //导航的数据源
    private val navList = mutableListOf<HomeNavBean>()

    //banner的数据源
    private val bannerUrls = mutableListOf<String>()

    private val hotList = mutableListOf<HomeGoodsBean>()
    private lateinit var hotAdapter: HomeHotAdapter

    //上拉加载更多时需要的更新页码
    private var currentPage = 1
    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initData() {
        viewModel.getHomeBanner()//请求首页banner
        viewModel.getHomeGoodsList(0, currentPage, 10)//请求首页商品列表
        viewModel.getHomeNav()//请求首页导航
        viewModel.getHomeHot(0, 1, 10)//请求热销商品列表

        viewModel.getHomeHotGoodsListSuccess.observe(this) {
            if (it.code == 200) {
                hotList.clear()
                hotList.addAll(it.data)
                hotAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getHomeHotGoodsListFailed.observe(this) {

        }

        viewModel.getHomeNavSuccess.observe(this) {
            if (it.code == 200) {
                navList.clear()
                navList.addAll(it.data[0].data!!)
                navAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getHomeNavFailed.observe(this) {
            Log.i("TagA", "获取首页导航失败:$it")
        }

        viewModel.getHomeBannerSuccess.observe(this) {
            if (it.code == 200) {
                bannerUrls.clear()
                it.data.forEach { bannerBean ->
                    bannerUrls.add(bannerBean.imagePath)
                }
                dataBinding.homeBanner.setImages(bannerUrls)//banner接受数据源的时候,只接收图片地址的list,所以需要转化
                dataBinding.homeBanner.start()
            }


        }

        viewModel.getHomeBannerFailed.observe(this) {
            Log.i("TagA", "bannerF:$it")
        }

        viewModel.getHomeGoodsListSuccess.observe(this) {
            if (it.code == 200) {
                //当currentPage等于1的时候,要么是初始化的状态,要么是下拉刷新的状态,需要重置list的数据源
                if (currentPage == 1) {
                    homeGoodsList.clear()
                }
                dataBinding.homeSrl.finishRefresh()
                dataBinding.homeSrl.finishLoadMore()
                homeGoodsList.addAll(it.data)
                homeGoodsAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getHomeGoodsListFailed.observe(this) {
            Log.i("TagA", "goodsF:$it")
        }
    }

    override fun initView() {
        //初始化商品列表
        dataBinding.homeRv.layoutManager = GridLayoutManager(requireContext(), 2)
        homeGoodsAdapter = HomeGoodsAdapter(homeGoodsList)
        dataBinding.homeRv.adapter = homeGoodsAdapter
        homeGoodsAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireContext(), DetailActivity::class.java)
            intent.putExtra(Const.PARAM_GOODS_ID, homeGoodsList[position].id)
            startActivity(intent)
        }

        //初始化banner
        dataBinding.homeBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)//设置指示器风格.CIRCLE圆点指示器,NUM数字指示器
        dataBinding.homeBanner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (context != null && imageView != null) {
                    ImageUtils.loadImage(context, path.toString(), imageView)
                }
            }
        })
        dataBinding.homeBanner.setDelayTime(2000)//设置banner播放时间
        dataBinding.homeBanner.setIndicatorGravity(BannerConfig.CENTER)//设置指示器位置

        //初始化刷新框架
        dataBinding.homeSrl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                //如果刷新的时候,在加载更多,就停止加载,只让框架单纯的刷新
                if (refreshLayout.isLoading) {
                    refreshLayout.finishLoadMore()
                }
                currentPage = 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (refreshLayout.isRefreshing) {
                    refreshLayout.finishRefresh()
                }
                currentPage += 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }
        })

        //首页导航初始化
        dataBinding.homeNavRv.layoutManager = GridLayoutManager(requireContext(), 5)
        navAdapter = HomeNavAdapter(navList)
        dataBinding.homeNavRv.adapter = navAdapter

        //首页热销初始化
        dataBinding.homeHotGoodsRv.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        hotAdapter = HomeHotAdapter(hotList)
        dataBinding.homeHotGoodsRv.adapter = hotAdapter
        hotAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireContext(), DetailActivity::class.java)
            intent.putExtra(Const.PARAM_GOODS_ID, homeGoodsList[position].id)
            startActivity(intent)
        }

        //首页搜索点击事件
        dataBinding.homeSearchTv.setOnClickListener {
            val intent = Intent(requireContext(), SearchActivity::class.java)
            startActivity(intent)
        }
    }

    override fun getViewModel(): Class<HomeViewModel> {
        return HomeViewModel::class.java
    }
}